<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">学号：</span>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.username"
      />
      <span class="search-label">姓名：</span>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
      />
      <span class="search-label">班级：</span>
      <el-select
        v-model="params.className"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur2"
        @clear="selectClear2"
        @change="selectChange2"
      >
        <el-option
          v-for="(item, index) in classes"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      <span class="search-label" style="margin-left: 5px">学期：</span>
      <el-select
        v-model="params.termName"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur"
        @clear="selectClear"
        @change="selectChange"
      >
        <el-option
          v-for="(item, index) in terms"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      <span class="search-label" style="margin-left: 4px">课程：</span>
      <el-select
        v-model="params.courseName"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur3"
        @clear="selectClear3"
        @change="selectChange3"
      >
        <el-option
          v-for="(item, index) in courses"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>
    <div class="search-container">
      <span class="search-label">是否及格：</span>
      <el-select v-model="params.isPass">
        <el-option
          v-for="item in passList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <span class="search-label" style="margin-left: 10px">状态：</span>
      <el-select v-model="params.verification_status">
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <span class="search-label" style="margin-left: 10px">学号排序：</span>
      <el-select v-model="params.usernameOrder">
        <el-option
          v-for="item in usernameOrderList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <span class="search-label" style="margin-left: 10px">成绩排序：</span>
      <el-select v-model="params.scoreValueOrder">
        <el-option
          v-for="item in scoreValueOrderList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <el-button
        type="primary"
        class="search-btn"
        @click="search"
        style="margin-left: 30px"
        >查询</el-button
      >
    </div>
    <div class="tag-group">
      <span class="tag-group__title"></span>
      <el-tag effect="plain"> 最高分:{{ this.statistics.maxScore }} </el-tag>
      <el-tag effect="plain"> 最低分:{{ this.statistics.minScore }} </el-tag>
      <el-tag effect="plain"> 平均分:{{ this.statistics.avgScore }} </el-tag>
      <el-tag effect="plain">
        及格率:
        {{
          (
            (this.statistics.passCount / this.statistics.totalCount) *
            100
          ).toFixed(2)
        }}%
      </el-tag>
      <el-tag effect="plain"> 及格人数:{{ this.statistics.passCount }} </el-tag>
      <el-tag effect="plain">
        不及格人数:{{ this.statistics.nopassCount }}
      </el-tag>
      <el-tag effect="plain"> 总人数:{{ this.statistics.totalCount }} </el-tag>
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button @click="batchDelete">批量删除</el-button>
      <el-button @click="batchPass">批量审核通过</el-button>
      <el-button @click="batchNoPass">批量审核未通过</el-button>
      <el-button @click="handleExportExcel">导出excel表</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="学号" prop="username" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="班级" prop="className" />
        <el-table-column label="学期" prop="termName" />
        <el-table-column label="课程名" prop="courseName" />
        <el-table-column label="分数" prop="scoreValue" />
        <el-table-column
          label="状态"
          prop="verificationStatus"
          :formatter="formatStatus"
        />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="edit(scope.row.scoreId, scope.row.scoreValue)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="deleteOne(scope.row.scoreId)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-if="
                scope.row.verificationStatus === 3
              "
              @click="passOne(scope.row.scoreId)"
              >审核通过</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-if="
                scope.row.verificationStatus === 3
              "
              @click="noPassOne(scope.row.scoreId)"
              >审核未通过</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加或修改操作日志记录对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <span slot="title">修改分数</span>
      <el-form ref="form" :model="Form" :rules="Rules" label-width="80px">
        <el-form-item label="分数" prop="scoreValue">
          <el-input v-model="Form.scoreValue" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  scoresListTeacherAPI,
  passScoreAPI,
  noPassScoreAPI,
  updateScoreAPI,
  exportExcelAPI,
  deleteScoreAPI
} from "@/api/score";
import { getTermsListByTeacherAPI } from "@/api/term";
import { getCoursesListByTeacherAPI } from "@/api/course";
import { ClasseslistByTeacherAPI } from "@/api/classes";

export default {
  name: "Check_results",
  data() {
    return {
      items: [],
      statistics: {},
      open: false,
      Rules: {
        scoreValue: [
          {
            required: true,
            message: "请输入分数",
            trigger: "blur",
          },
          {
            pattern: /^-?\d+(\.\d+)?$/,
            message: "分数格式不正确",
            trigger: "blur",
          },
        ],
      },
      Form: {
        scoreId: "",
        
        scoreValue: "",
      },
      terms: [],
      courses: [],
      classes: [],
      // 审核表单参数
      statusList: [
        {
          text: "全部",
          value: null,
        },
        {
          text: "未审核",
          value: "0",
        },
        {
          text: "已通过",
          value: "1",
        },
        {
          text: "未通过",
          value: "2",
        },
        {
          text: "送审中",
          value: "3",
        },
      ],
      // 及格表单参数
      passList: [
        {
          text: "全部",
          value: null,
        },
        {
          text: "未及格",
          value: "0",
        },
        {
          text: "已及格",
          value: "1",
        },
      ],
      usernameOrderList: [
        {
          text: "不排序",
          value: null,
        },
        {
          text: "升序",
          value: "0",
        },
        {
          text: "降序",
          value: "1",
        },
      ],
      scoreValueOrderList: [
        {
          text: "不排序",
          value: null,
        },
        {
          text: "升序",
          value: "0",
        },
        {
          text: "降序",
          value: "1",
        },
      ],
      total: 0, //页总数
      list: [], //列表
      params: {
        //参数
        page: 1,
        pageSize: 2,
        termName: "",
        className: "",
        courseName: "",
        name: "",
        username: "",
        isPass: null,
        verification_status: null,
        usernameOrder: null,
        scoreValueOrder: null,
      },
    };
  },
  created() {
    //获取成绩
    this.scoresListTeacher();
    //获取学期数据
    this.getTermsListByTeacher();
    //获取班级数据
    this.ClasseslistByTeacher();
    this.getCoursesListByTeacher();
  },
  methods: {
    handleExportExcel() {
      exportExcelAPI(this.params)
        .then(response => {
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'scores.xlsx';
          link.click();

          window.URL.revokeObjectURL(link.href);
        })
        .catch(error => {
          console.error('Failed to export Excel:', error);
        });
    },
    //单个删除
    deleteOne(id) {
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await deleteScoreAPI(id);
          this.$message.success("删除成功");
          if (this.list.length == 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.scoresListTeacher();
        })
        .catch(() => {});
    },
    //批量删除
    batchDelete() {
      if (this.selecttionVal.length <= 0) {
        this.$message.warning("请先选择要删除的数据");
        return;
      }
      const ids = this.selecttionVal.map((item) => {
        return item.scoreId;
      });
      this.$confirm("您确定要删除此数据吗?", "提示")
        .then(async () => {
          await deleteScoreAPI(ids.join(","));
          this.$message.success("批量删除成功");
          this.scoresListTeacher();
          if (
            this.list.length == this.selecttionVal.length &&
            this.params.page > 1
          ) {
            this.params.page--;
          }
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.Form.scoreValue = "";
    },
    //提交表格
    submitForm() {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        //修改操作
        await updateScoreAPI(this.Form);
        this.$message.success("修改成功");
        this.open = false;
        this.scoresListTeacher();
      });
    },
    //编辑按钮
    async edit(scoreId, scoreValue) {
      this.Form.scoreId = scoreId;
      this.Form.scoreValue = scoreValue;
      this.open = true;
    },
    //单个通过
    passOne(id) {
      this.$confirm("您确定要通过此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await passScoreAPI(id);
          this.$message.success("通过成功");
          if (this.list.length == 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.scoresListTeacher();
        })
        .catch(() => {
          // console.log('点击取消');
        });
    },
    //单个未通过
    noPassOne(id) {
      this.$confirm("您确定要未通过此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await noPassScoreAPI(id);
          this.$message.success("未通过成功");
          if (this.list.length == 1 && this.params.page > 1) {
            this.params.page--;
          }
          this.scoresListTeacher();
        })
        .catch(() => {
          // console.log('点击取消');
        });
    },
    //批量通过
    batchPass() {
      if (this.selecttionVal.length <= 0) {
        this.$message.warning("请先选择要通过的数据");
        return;
      }
      const ids = this.selecttionVal.map((item) => {
        return item.scoreId;
      });
      this.$confirm("您确定要通过此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await passScoreAPI(ids.join(","));
          this.$message.success("批量通过成功");
          if (
            this.list.length == this.selecttionVal.length &&
            this.params.page > 1
          ) {
            this.params.page--;
          }
          this.scoresListTeacher();
        })
        .catch(() => {
          // console.log('点击取消');
        });
    },
    //批量未通过
    batchNoPass() {
      if (this.selecttionVal.length <= 0) {
        this.$message.warning("请先选择要未通过的数据");
        return;
      }
      const ids = this.selecttionVal.map((item) => {
        return item.scoreId;
      });
      this.$confirm("您确定要通过此数据吗?", "提示")
        .then(async () => {
          // console.log('点击确定');
          await noPassScoreAPI(ids.join(","));
          this.$message.success("批量通过成功");
          if (
            this.list.length == this.selecttionVal.length &&
            this.params.page > 1
          ) {
            this.params.page--;
          }
          this.scoresListTeacher();
        })
        .catch(() => {
          // console.log('点击取消');
        });
    },
    //获取选择的数据
    handleSelectionChange(val) {
      this.selecttionVal = val;
    },
    //获取成绩管理
    async scoresListTeacher() {
      const res = await scoresListTeacherAPI(this.params);
      this.total = res.data.total;
      this.list = res.data.records;
      this.statistics = res.data.statistics;
    },
    //多选框输入值
    selectBlur(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.termName = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear() {
      this.params.termName = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange(val) {
      this.params.termName = val;
      this.$forceUpdate();
    },
    //多选框输入值
    selectBlur2(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.className = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear2() {
      this.params.className = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange2(val) {
      this.params.className = val;
      this.$forceUpdate();
    },
    //多选框输入值
    selectBlur3(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.courseName = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear3() {
      this.params.courseName = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange3(val) {
      this.params.courseName = val;
      this.$forceUpdate();
    },
    // 获取课程列表
    async getCoursesListByTeacher() {
      const res = await getCoursesListByTeacherAPI();
      this.courses = res.data;
    },
    //获取班级列表
    async ClasseslistByTeacher() {
      const res = await ClasseslistByTeacherAPI();
      this.classes = res.data;
    },
    //获取学期数据
    async getTermsListByTeacher() {
      const res = await getTermsListByTeacherAPI();
      this.terms = res.data;
    },
    //点击查询按钮
    search() {
      this.params.page = 1;
      this.scoresListTeacher();
    },
    //计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    //页数改变
    handleCurrentChange(val) {
      this.params.page = val;
      this.scoresListTeacher();
    },
    //页条数改变
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.scoresListTeacher();
    },
    //格式化状态
    formatStatus(row) {
      const MAP = {
        0: "未审核",
        1: "已通过",
        2: "未通过",
        3: "送审中",
      };
      return MAP[row.verificationStatus];
    },
  },
};
</script>


<style lang="scss" scoped>
.tag-group {
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  flex-wrap: wrap; /* 允许标签换行 */
  width: 100%; /* 占满父容器的宽度 */
}

.tag-group__title {
  width: 100%; /* 标题占据整行宽度 */
  text-align: left; /* 文字左对齐 */
  margin-bottom: 10px; /* 可选：增加标题与标签之间的间距 */
}

.el-tag {
  margin-right: 10px; /* 设置标签之间的右侧间距 */
  margin-bottom: 10px; /* 设置标签之间的下方间距 */
}

.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>